package logic.netSerer.GUI.nettyServer;

import java.net.InetSocketAddress;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.util.CharsetUtil;
import logic.util.EasyLog;

public class NettyClient {
	private ScheduledExecutorService excutor=Executors.newScheduledThreadPool(1);
	public static final int PORT=8301;
	public static final String IP="localhost";
	public static EventLoopGroup group=new NioEventLoopGroup();
	
	public void connect(int port, String host, final int index) throws Exception{
		//配置NIO线程组
		try{
			Bootstrap bootstrap=new Bootstrap();
			bootstrap.group(group).channel(NioSocketChannel.class).option(ChannelOption.TCP_NODELAY,true)
				.handler(new ChannelInitializer<SocketChannel>() {
					@Override
					protected void initChannel(SocketChannel ch) throws Exception {
						ChannelPipeline channelPipeline=ch.pipeline();
						channelPipeline.addLast(new StringDecoder(CharsetUtil.UTF_8));
						channelPipeline.addLast(new StringEncoder(CharsetUtil.UTF_8));
						//业务处理器
						channelPipeline.addLast(new NettyClientHandler(index));
					}
				});
			//发起异步连接
			ChannelFuture future=bootstrap.connect(new InetSocketAddress(host, port));
			future.channel().closeFuture().sync();//??
			
		}finally {
			excutor.execute(new Runnable() {
				@Override
				public void run() {
					try{
						TimeUnit.SECONDS.sleep(1);
						try{
							//connect(PORT, IP, index);
						}catch (Exception e) {
							EasyLog.info(getClass(), "重连发生异常:{}", e);
						}
					}catch (InterruptedException e) {
						EasyLog.info(getClass(), "连接中断异常:{}", e);
					}
				}
			});
		}
	}
	
	public static void main(String...args)throws Exception{
		for(int i=0;i<3;i++){
			new NettyClient().connect(PORT, IP, i+1);
		}
	}
	
	
	
}
